package com.dublbo.addressbook.frame;

import com.dublbo.addressbook.entity.ContactPerson;
import com.dublbo.addressbook.frame.group.*;
import com.dublbo.addressbook.frame.person.*;
import com.dublbo.addressbook.util.Constant;
import com.dublbo.addressbook.util.FileOperation;
import com.dublbo.jpSwing.*;
import com.dublbo.jpSwing.layout.JpColumnLayout;
import com.dublbo.jpSwing.layout.JpRowLayout;
import com.dublbo.jpSwing.popup.JpPopupPanel;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;

/**
 * 所有联系人主面板类：主要显示导航栏和联系人列表
 *
 * @author Administrator
 * create_time 2020/07/09
 */
public class CPersonMainPanel extends JPanel {
    public CPersonNavPanel personNavPanel;  // 联系人导航栏
    public GroupNavPanel groupNavPanel;  // 联系组导航栏
    public CPersonTableView tableView = new CPersonTableView();  // 用于显示数据的表格
    public String groupFilter;  // 所属组过滤
    public JTabbedPane left_menu; // 左边菜单栏，有时候可能会需要修改

    public CPersonMainPanel(String groupFilter, JTabbedPane left_menu) {
        this.groupFilter = groupFilter;
        this.left_menu = left_menu;

        this.setLayout(new BorderLayout());
        // 添加 导航栏 对象
        if (groupFilter == null) {
            System.out.println("程序错误！");
            System.exit(200);
        } else if (groupFilter.equals("") || groupFilter.equals(Constant.BLANK_REPLACE)) {
            this.groupNavPanel = null;
            this.personNavPanel = new CPersonNavPanel();
            addPersonNavPanelAction(); // 给导航栏中的组件添加监听事件
            this.add(personNavPanel, BorderLayout.PAGE_START);
        } else {
            this.personNavPanel = null;
            this.groupNavPanel = new GroupNavPanel();
            addGroupNavPanelAction();
            this.add(groupNavPanel, BorderLayout.PAGE_START);
        }
        this.add(initCenter(), BorderLayout.CENTER);
        this.add(initBottom(), BorderLayout.PAGE_END);
    }

    private void addPersonNavPanelAction() {
        //给 新建联系人 按钮添加点击事件
        this.personNavPanel.addButton.addActionListener((e) -> onAddPerson());
        // 给 删除 按钮添加点击事件
        this.personNavPanel.delButton.addActionListener((e) -> onDelPerson());
        // 给 复制到组 按钮添加点击事件
        this.personNavPanel.copyToGroupButton.addActionListener(this::onCopyToGroup);
        // 给 刷新 按钮添加点击事件
        this.personNavPanel.reloadButton.addActionListener((e) -> onReload());
        // 给 搜索 按钮事件
        this.personNavPanel.searchButton.addActionListener((e) -> {
            String tmp = this.personNavPanel.searchEdit.getText().trim();
            if (("").equals(tmp)) {
                JpToaster.show(this, JpToaster.WARN, "请输入内容后搜索！");
                return;
            }
            onQuery(tmp);
        });
        // 给 导入导出 按钮添加事件
        this.personNavPanel.im_exportBtn.addActionListener(this::onImportOrExport);
    }


    private void addGroupNavPanelAction() {
        //给 新建组 按钮添加点击事件
        this.groupNavPanel.addGroupBtn.addActionListener((e) -> onAddGroup());
        // 给 删除组 按钮添加点击事件
        this.groupNavPanel.delGroupBtn.addActionListener((e) -> onDelGroup());
        // 给 编辑组 按钮添加点击事件
        this.groupNavPanel.editGroupBtn.addActionListener((e) -> onEditGroup());
        // 给 复制到组 按钮添加点击事件
        this.groupNavPanel.copyToGroupBtn.addActionListener(this::onCopyToGroup);
        // 给 移动到组 按钮添加点击事件
        this.groupNavPanel.moveToGroupBtn.addActionListener(this::onMoveToGroup);
        // 给 删除 按钮添加点击事件
        this.groupNavPanel.delPersonBtn.addActionListener((e) -> onDelPerson());
        // 给刷新按钮添加点击事件
        this.groupNavPanel.reloadBtn.addActionListener((e) -> onReload());
        // 监听搜索按钮事件
        this.groupNavPanel.searchBtn.addActionListener((e) -> {
            String tmp = this.groupNavPanel.searchEdit.getText().trim();
            if (("").equals(tmp)) {
                JpToaster.show(this, JpToaster.WARN, "请输入内容后搜索！");
                return;
            }
            onQuery(tmp);
        });
    }

    private JComponent initCenter() {
        JpPanel panel = new JpPanel();
        panel.setLayout(new JpColumnLayout(4));
        panel.padding(0);

        JScrollPane scroll = new JScrollPane(tableView);
        panel.add(scroll, "1w");

        scroll.getViewport().setOpaque(true);
        scroll.getViewport().setBackground(new Color(0xFCFCFC));

        // 右键点击表格
        tableView.setRightClickedListener((view, row, col, evt) -> {
            // 保存点击的联系人对象（查询文件）
            ContactPerson person = FileOperation.getCPersonByKey(tableView.model.getValueAt(row, 1).toString());
            if (person == null) {
                JpToaster.show(view, JpToaster.ERROR, "系统内部错误，请刷新后重试！");
                return;
            }
            // 弹出右键菜单界面
            CPersonInfoPopupPanel infoPanel = new CPersonInfoPopupPanel(CPersonMainPanel.this, person, row, evt.getX(), evt.getY());
            infoPanel.showPopup(view, evt.getX(), evt.getY());
        });

        onReload();
        return panel;
    }

    private JComponent initBottom() {
        JpPanel panel = new JpPanel();
        panel.setLayout(new JpRowLayout(4));
        panel.padding(2);
        panel.preferredHeight(30);
        return panel;
    }

    /************************** 按钮事件调用函数 **************************/
    private void onAddGroup() {
        GroupAddDialog dlg = new GroupAddDialog(this, "");
        String groupName = dlg.exec(); // 接受返回的联系组名称
        if (groupName != null && !groupName.equals("")) {
            GroupInsertTask task = new GroupInsertTask(this);
            task.execute(groupName);
        } else {
            System.out.println("添加联系组失败！groupName为空");
        }
    }

    private void onEditGroup() {
        GroupAddDialog dlg = new GroupAddDialog(this, groupFilter);
        String groupName = dlg.exec(); // 接受返回的联系组名称
        System.out.println("onEditGroup====== groupFilter=" + groupFilter + ", groupName=" + groupName);
        if (groupName != null && !groupName.equals("")) {
            GroupUpdateTask task = new GroupUpdateTask(this);
            task.execute(groupFilter, groupName);
        } else {
            System.out.println("修改联系组失败！groupName为空");
        }
    }

    private void onDelGroup() {
        GroupDeleteDialog dlg = new GroupDeleteDialog(this);
        int select = dlg.exec();
        System.out.println("onDelGroup====== select=" + select + ", groupName=" + this.groupFilter);
        if (select > 0) {
            String[] delPersonArr = null;
            if (select == 2) { // 删除该组及该组的所有联系人
                int len = this.tableView.getRowCount();
                if (len > 0) {
                    delPersonArr = new String[len];
                    for (int i = 0; i < len; i++) {
                        delPersonArr[i] = this.tableView.getValueAt(i, 1).toString();
                    }
                }
            }
            GroupDeleteTask task = new GroupDeleteTask(this);
            task.execute(groupFilter, delPersonArr);
        }
    }

    public void onReload() {
        this.tableView.clear();
        CPersonQueryTask task = new CPersonQueryTask(this);
        task.execute("", this.groupFilter);
    }

    private void onCopyToGroup(ActionEvent e) {
        int[] selectedRows = this.tableView.getSelectedRows();
        if (selectedRows != null && selectedRows.length > 0) {
            JpButton btn = (JpButton) e.getSource();
            CopyToGroupPopupPanel popupPanel = new CopyToGroupPopupPanel(this, selectedRows);
            popupPanel.showPopup(this, btn.getX(), btn.getY() + btn.getHeight());
        } else {
            JpToaster.show(this, JpToaster.WARN, "请先选择联系人！");
        }
    }

    private void onImportOrExport(ActionEvent e) {
        JButton btn = (JButton) e.getSource();
        ImportOrExportPopupPanel popupPanel = new ImportOrExportPopupPanel(this);
        popupPanel.showPopup(this, btn.getX() + btn.getWidth(), btn.getY() + btn.getHeight());
    }

    private void onMoveToGroup(ActionEvent e) {
        int[] selectedRows = this.tableView.getSelectedRows();
        if (selectedRows != null && selectedRows.length > 0) {
            JpButton btn = (JpButton) e.getSource();
            MoveToGroupPopupPanel ctgp = new MoveToGroupPopupPanel(this, selectedRows, groupFilter);
            ctgp.showPopup(this, btn.getX(), btn.getY() + btn.getHeight());
        } else {
            JpToaster.show(this, JpToaster.WARN, "请先选择联系人！");
        }
    }

    private void onDelPerson() {
        int[] rowIndexes = this.tableView.getSelectedRows();
        if (rowIndexes == null || rowIndexes.length <= 0) {
            JpToaster.show(this, JpToaster.WARN, "请选择要删除的联系人！");
            return;
        }

        String[] keys = new String[rowIndexes.length];
        for (int i = 0; i < rowIndexes.length; i++) {
            // 获取 姓名
            keys[i] = this.tableView.getValueAt(rowIndexes[i], 1).toString();
        }

        int result = JOptionPane.showConfirmDialog(  // 是：0 否：1 取消：-1
                this,
                "确认删除择联系人：\n『 " + String.join(" , ", keys) + " 』？",
                "提示",
                JOptionPane.YES_NO_OPTION
        );

        if (result == 0) { // 选择 “是”
            CPersonDeleteTask task = new CPersonDeleteTask(this);
            task.execute(rowIndexes, keys);
        }
    }

    private void onAddPerson() {
        CPersonAddDialog dlg = new CPersonAddDialog(tableView);
        ContactPerson person = dlg.exec();
        if (person != null) {
            CPersonInsertTask task = new CPersonInsertTask(this);
            task.execute(person);
        }
    }

    private void onQuery(String nameFilter) {
        System.out.println("onQuery====== nameFilter=" + nameFilter);
        this.tableView.clear();  // 清空联系人列表
        CPersonQueryTask task = new CPersonQueryTask(this);
        task.execute(nameFilter, this.groupFilter);
    }
}
